package com.fow.core.platform.web.pagination;

import com.fow.core.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Greg.Chen on 2015/1/15.
 */
public class PaginationForm {
    private final Logger logger = LoggerFactory.getLogger(PaginationForm.class);

    @NotNull
    @Min(0)
    private int pageIndex;

    @NotNull
    @Min(0)
    private int pageSize;

    private List<String> sorting;

    public int getPageIndex() {
        return pageIndex;
    }

    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public Map<String, Object> getQueryMap(){
        Map<String, Object> query = new HashMap<>();

        Field[] fields = this.getClass().getDeclaredFields();

        query.put("startIndex",this.pageSize * this.pageIndex);
        query.put("pageSize",this.pageSize);
        if(sorting != null)
            query.put("sorting", sorting);

        try {
            for(Field field : fields){
                field.setAccessible(true);
                if(field.getType().equals(String.class) && !StringUtils.hasText((String) field.get(this)))
                    continue;
                else if(field.get(this) == null)
                    continue;
                query.put(field.getName(),field.get(this));
            }
        } catch (IllegalAccessException e) {
            logger.warn(e.getMessage());
        }

        return query;
    }

    public List<String> getSorting() {
        return sorting;
    }

    public void setSorting(List<String> sorting) {
        this.sorting = sorting;
    }
}
